<template>
  <div>
    <Title :title="title"></Title>
    <div ref="left1" style="height: 300px;"></div>
  </div>
</template>

<script setup>
import { Line } from '@antv/g2plot';
import Title from './Title.vue';
import moment from 'moment';
import { ref, onMounted } from 'vue';
import { get } from '@/utils/request';

const title = ref('南通市崇川区温湿度实时曲线');
const left1 = ref(null);
const TempHumidityData = ref([]);

const loadLine = () => {
  // 计算Y轴动态范围
  const tempValues = TempHumidityData.value.filter(d => d.type === 'temperature').map(d => d.value);
  const humidityValues = TempHumidityData.value.filter(d => d.type === 'humidity').map(d => d.value);
  
  const minTemp = Math.min(...tempValues);
  const maxTemp = Math.max(...tempValues);
  const minHumidity = Math.min(...humidityValues);
  const maxHumidity = Math.max(...humidityValues);
  
  // 调整Y轴范围，使变化更明显
  const tempPadding = Math.max((maxTemp - minTemp) * 0.3, 2); // 至少保留2度的范围
  const humidityPadding = Math.max((maxHumidity - minHumidity) * 0.3, 5); // 至少保留5%的范围

  const line = new Line(left1.value, {
    data: TempHumidityData.value,
    xField: 'insert_time',
    yField: 'value',
    seriesField: 'type',
    color: ['#FF7D00', '#00B42A'], // 修改了曲线颜色
    xAxis: {
      label: {
        rotate: -45,
        style: {
          fill: 'white',
          fontSize: 12
        }
      }
    },
    yAxis: [
      {
        name: '温度(°C)',
        position: 'left',
        min: minTemp - tempPadding,
        max: maxTemp + tempPadding,
        label: {
          style: {
            fill: '#FF7D00', // 修改了温度Y轴标签颜色
            fontSize: 12
          }
        }
      },
      {
        name: '湿度(%)',
        position: 'right',
        min: minHumidity - humidityPadding,
        max: maxHumidity + humidityPadding,
        label: {
          style: {
            fill: '#00B42A', // 修改了湿度Y轴标签颜色
            fontSize: 12
          },
          formatter: (v) => `${v}%`
        }
      }
    ],
    legend: {
      position: 'bottom',
      itemName: {
        style: {
          fill: 'white'
        }
      }
    },
    smooth: true,
    lineStyle: {
      lineWidth: 2
    },
    point: {
      size: 4,
      shape: 'circle'
    },
    tooltip: {
      domStyles: {
        "g2-tooltip": {
          background: '#272E3B', // 修改了tooltip背景色
          fontSize: '16px',
          color: 'white'
        }
      },
      formatter: (datum) => {
        return {
          name: datum.type === 'temperature' ? '温度' : '湿度',
          value: datum.value + (datum.type === 'temperature' ? '°C' : '%')
        };
      }
    },
    animation: {
      appear: {
        animation: 'wave-in',
        duration: 5000,
      },
    },
    interactions: [{ type: 'marker-active' }]
  });

  line.render();
}

const getData = async () => {
  try {
    let res = await get('/dashboard/pageQueryData', {page: 1, pageSize: 1000});
    console.log(res, '接口返回数据');
    if (res.status === 200 && res.data && res.data.list) {
      // 按时间分组处理数据
      const timeGroups = {};
      
      res.data.list.forEach((item) => {
        const timeStr = moment(item.insert_time).format('HH:mm');
        
        if (!timeGroups[timeStr]) {
          timeGroups[timeStr] = {
            time: timeStr,
            temperatures: [],
            humidities: []
          };
        }
        
        if (item.temperature) {
          timeGroups[timeStr].temperatures.push(parseFloat(item.temperature));
        }
        
        if (item.humidity) {
          timeGroups[timeStr].humidities.push(parseFloat(item.humidity));
        }
      });
      
      // 计算每个时间点的平均值
      let processedData = [];
      Object.values(timeGroups).forEach(group => {
        if (group.temperatures.length > 0) {
          const avgTemp = group.temperatures.reduce((a, b) => a + b, 0) / group.temperatures.length;
          processedData.push({
            insert_time: group.time,
            type: 'temperature',
            value: parseFloat(avgTemp.toFixed(1))
          });
        }
        
        if (group.humidities.length > 0) {
          const avgHumidity = group.humidities.reduce((a, b) => a + b, 0) / group.humidities.length;
          processedData.push({
            insert_time: group.time,
            type: 'humidity',
            value: parseFloat(avgHumidity.toFixed(1))
          });
        }
      });
      
      // 按时间排序
      processedData.sort((a, b) => {
        return moment(a.insert_time, 'HH:mm').valueOf() - moment(b.insert_time, 'HH:mm').valueOf();
      });
      
      TempHumidityData.value = processedData;
    } else {
      console.error('接口返回数据格式不正确');
    }
  } catch (error) {
    console.error('获取数据失败:', error);
  }
}

onMounted(async () => {
  await getData();
  loadLine();
});
</script>

<style lang="less" scoped></style>